using RabbitMQ.Client;

namespace Beauty.Net.RabbitMQ.Headers
{
    /// <summary>
    /// 头部交换模式消费者
    /// </summary>
    public class HeadersConsumer<T> : RabbitMQConsumerBase<T>
    {
        private readonly Dictionary<string, object> _bindingHeaders;
        private readonly bool _matchAny;

        public HeadersConsumer(IRabbitMQConnectionManager connectionManager,
                              string exchangeName,
                              string queueName,
                              Dictionary<string, object> bindingHeaders,
                              MessageHandler<T> messageHandler,
                              bool matchAny = false,
                              bool autoAck = false)
            : base(connectionManager, exchangeName, queueName, string.Empty, messageHandler, autoAck)
        {
            _bindingHeaders = bindingHeaders;
            _matchAny = matchAny;
        }

        protected override void SetupExchangeAndQueue()
        {
            if (_channel == null) throw new InvalidOperationException("Channel not initialized");
            
            // 声明头部交换机
            _channel.ExchangeDeclare(exchange: ExchangeName,
                                   type: ExchangeType.Headers,
                                   durable: true,
                                   autoDelete: false,
                                   arguments: null);

            // 声明队列
            _channel.QueueDeclare(queue: QueueName,
                                durable: true,
                                exclusive: false,
                                autoDelete: false,
                                arguments: null);

            // 准备绑定参数
            var arguments = new Dictionary<string, object>(_bindingHeaders);
            // 添加匹配类型参数
            arguments["x-match"] = _matchAny ? "any" : "all";

            // 将队列绑定到交换机
            _channel.QueueBind(queue: QueueName,
                              exchange: ExchangeName,
                              routingKey: string.Empty,
                              arguments: arguments);
        }
    }
}